package rad.framework.seam;

import java.awt.Color;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.util.Iterator;

import javax.persistence.EntityManager;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.general.PieDataset;

public class PieChart {

	private EntityManager entityManager;

	private DefaultPieDataset chart;

	private String eql;

	private int width = 250;

	private int height = 150;

	public PieChart(EntityManager entityManager, String className,
			String property, int width, int height) {
		this(entityManager, className, property);
		this.width = width;
		this.height = height;
	}

	public PieChart(EntityManager entityManager, String className,
			String property) {
		super();

		this.entityManager = entityManager;

		StringBuffer buf = new StringBuffer();
		buf.append("select c.");
		buf.append(property);
		buf.append(", count(c) from ");
		buf.append(className);
		// TODO permission filter and outer join
		buf.append(" c where c.");
		buf.append(property);
		buf.append(" is not null group by c.");
		buf.append(property);
		this.eql = buf.toString();

		chart = new DefaultPieDataset();

		Iterator results = this.entityManager.createQuery(this.eql)
				.getResultList().iterator();
		while (results.hasNext()) {
			Object[] row = (Object[]) results.next();
			chart.setValue((row[0] == null ? "blank" : row[0].toString()),
					(Number) row[1]);
		}
	}

	public PieDataset getChart() {
		return chart;
	}


	public BufferedImage getImage(Long width, Long height) {
		JFreeChart chart = ChartFactory.createPieChart("", getChart(), true,
				true, false);
		chart.setBackgroundPaint(Color.white);
		chart.setBorderVisible(false);
		return chart.createBufferedImage(width.intValue(), height.intValue());
	}
	
	public Image getImage() {
		return getImage(new Long(width), new Long(height));
	}
	
	public byte[] getData(Long width, Long height) {
		try {
			return ChartUtilities.encodeAsPNG(getImage(width, height));
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	public byte[] getData() {
		return getData(new Long(350), new Long(250));
	}
}
